package com.satchi.commons;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
public class SessionInterceptor implements Filter  {

    private SessionFactory sf = null;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        
        try{
            if (sf.getCurrentSession()==null){
                sf.openSession();
            }else{
                sf.getCurrentSession().beginTransaction();        
            }
            chain.doFilter(request, response);
            sf.getCurrentSession().getTransaction().commit();
        }catch(StaleObjectStateException ex){
            throw ex;
        }catch(Throwable tx){
            tx.printStackTrace();
            try{
                if(sf.getCurrentSession().getTransaction().isActive()){
                    sf.getCurrentSession().getTransaction().rollback();
                }
            }catch(Throwable rbEx){
                System.err.println(rbEx.toString());
            }
        }
    }

    public void init(FilterConfig arg0) throws ServletException {    
        sf = HibernateUtil.getSessionFactory();
    }
    
    public void destroy() {
        
    }

}

